// 余额流水页面混入
import {
	getMockBalanceFlowList,
	getMockBalanceStats,
	getMockBalanceFlowDetail,
	exportBalanceFlow
} from '../api/balanceFlow'

export default {
	data() {
		return {
			// 页面状态
			loading: false,
			refreshing: false,
			loadingMore: false,
			hasMore: true,
			
			// 日期筛选
			dateType: 'day', // 'day' 或 'month'
			selectedDate: '',
			datePickerShow: false,
			
			// 搜索功能
			searchKeyword: '',
			showSearch: false,
			
			// 分页参数
			currentPage: 1,
			pageSize: 20,
			
			// 数据列表
			dataList: [],
			filteredList: [],
			displayList: [],
			
			// 统计数据
			statsData: {
				totalDeposit: 0,
				totalExpense: 0,
				availableBalance: 0
			},
			
			// 详情弹窗
			showDetailPopup: false,
			selectedItem: null,
			
			// 内容高度
			contentHeight: 400
		}
	},
	
	computed: {
		// 格式化选中日期显示
		formattedSelectedDate() {
			if (!this.selectedDate) {
				const today = new Date()
				if (this.dateType === 'month') {
					return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`
				} else {
					return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
				}
			}
			return this.selectedDate
		},
		
		// 总收入
		totalIncome() {
			return this.displayList
				.filter(item => item.rawAmount > 0)
				.reduce((sum, item) => sum + item.rawAmount, 0)
		},
		
		// 总支出
		totalExpense() {
			return Math.abs(this.displayList
				.filter(item => item.rawAmount < 0)
				.reduce((sum, item) => sum + item.rawAmount, 0))
		},
		
		// 交易笔数
		transactionCount() {
			return this.displayList.length
		}
	},
	
	onLoad() {
		this.initPage()
		this.loadBalanceFlowData()
	},
	
	onReady() {
		this.calculateContentHeight()
	},
	
	onPullDownRefresh() {
		this.onRefresh()
	},
	
	onReachBottom() {
		this.loadMore()
	},
	
	methods: {
		// 初始化页面
		async initPage() {
			this.loading = true
			try {
				// 设置默认日期
				this.setDefaultDate()
				
				// 并行加载数据和统计
				await Promise.allSettled([
					this.loadBalanceFlowData(),
					this.loadStatsData()
				])
			} catch (error) {
				console.error('初始化页面失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 设置默认日期
		setDefaultDate() {
			const today = new Date()
			if (this.dateType === 'month') {
				this.selectedDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`
			} else {
				this.selectedDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
			}
		},
		
		// 加载余额流水数据
		async loadBalanceFlowData(isLoadMore = false) {
			try {
				// const params = {
				// 	page: isLoadMore ? this.currentPage + 1 : 1,
				// 	pageSize: this.pageSize,
				// 	dateType: this.dateType,
				// 	selectedDate: this.selectedDate,
				// 	keyword: this.searchKeyword
				// }
				console.log('loadBalanceFlowData', this.vuex_basCus.code)
				const params = {
					cusCode: this.vuex_basCus.code,
					// dateType: this.dateType,
					ddate: this.selectedDate,
					pageNo: isLoadMore ? this.currentPage + 1 : 1,
					pageSize: this.pageSize
				}
				
				// const res = await getMockBalanceFlowList(params)

				const res = await this.$u.api.shop.shopGiftData(params)

				
				const newData = res.list || []
					
				if (isLoadMore) {
					this.dataList = [...this.dataList, ...newData]
					this.currentPage += 1
				} else {
					this.dataList = newData
					this.currentPage = 1
				}
				
				// 检查是否还有更多数据
				this.hasMore = newData.length === this.pageSize
				
				// 应用筛选
				this.applyFilters()
			} catch (error) {
				console.error('加载余额流水数据失败:', error)
				throw error
			}
		},
		
		// 加载统计数据
		async loadStatsData() {
			try {
				const params = {
					dateType: this.dateType,
					selectedDate: this.selectedDate
				}
				
				const res = await getMockBalanceStats(params)
				
				if (res.code === 200) {
					this.statsData = res.data
				}
			} catch (error) {
				console.error('加载统计数据失败:', error)
				// 统计数据加载失败不影响主要功能
			}
		},
		
		// 应用筛选
		applyFilters() {
			let filtered = [...this.dataList]
			
			// 搜索筛选
			if (this.searchKeyword) {
				const keyword = this.searchKeyword.toLowerCase()
				filtered = filtered.filter(item => 
					item.type.toLowerCase().includes(keyword) ||
					item.account.toLowerCase().includes(keyword) ||
					item.orderNo.toLowerCase().includes(keyword)
				)
			}
			
			this.filteredList = filtered
			this.displayList = filtered
		},
		
		// 切换日期类型
		async switchDateType(type) {
			if (this.dateType === type) return
			
			this.dateType = type
			this.setDefaultDate()
			
			this.loading = true
			try {
				await Promise.all([
					this.loadBalanceFlowData(),
					this.loadStatsData()
				])
			} catch (error) {
				console.error('切换日期类型失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 日期选择器变化处理
		onDatePickerChange(e) {
			this.selectedDate = e.detail.value
			this.onDateChange()
		},

		// 日期改变处理
		async onDateChange() {
			this.loading = true
			try {
				await Promise.all([
					this.loadBalanceFlowData(),
					this.loadStatsData()
				])
			} catch (error) {
				console.error('日期改变加载数据失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 刷新数据
		async onRefresh() {
			this.refreshing = true
			try {
				this.currentPage = 1
				this.hasMore = true
				await Promise.all([
					this.loadBalanceFlowData(),
					this.loadStatsData()
				])
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('刷新数据失败:', error)
				this.showError('刷新失败')
			} finally {
				this.refreshing = false
				uni.stopPullDownRefresh()
			}
		},
		
		// 加载更多
		async loadMore() {
			if (this.loadingMore || !this.hasMore) return
			
			this.loadingMore = true
			try {
				await this.loadBalanceFlowData(true)
			} catch (error) {
				console.error('加载更多失败:', error)
				this.showError('加载失败')
			} finally {
				this.loadingMore = false
			}
		},
		
		// 搜索处理
		handleSearch() {
			// 防抖处理
			clearTimeout(this.searchTimer)
			this.searchTimer = setTimeout(() => {
				this.applyFilters()
			}, 300)
		},
		
		// 清除搜索
		clearSearch() {
			this.searchKeyword = ''
			this.applyFilters()
		},
		
		// 切换搜索显示
		toggleSearch() {
			this.showSearch = !this.showSearch
			if (!this.showSearch) {
				this.clearSearch()
			}
		},
		
		// 行点击事件
		// async handleRowClick(item) {
		// 	try {
		// 		uni.showLoading({
		// 			title: '加载中...'
		// 		})
				
		// 		const res = await getMockBalanceFlowDetail(item.id)
				
		// 		if (res.code === 200) {
		// 			this.selectedItem = {
		// 				...item,
		// 				...res.data
		// 			}
		// 			this.showDetailPopup = true
		// 		}
		// 	} catch (error) {
		// 		console.error('获取详情失败:', error)
		// 		this.showError('获取详情失败')
		// 	} finally {
		// 		uni.hideLoading()
		// 	}
		// },
		
		// 计算内容高度
		calculateContentHeight() {
			const systemInfo = uni.getSystemInfoSync()
			const windowHeight = systemInfo.windowHeight
			// 减去导航栏、筛选区域、数据展示区域、明细标题等高度
			this.contentHeight = windowHeight - 400
		},
		
		// 格式化金额
		formatAmount(amount) {
			if (amount === null || amount === undefined) return '0.00'
			
			const number = parseFloat(amount)
			if (isNaN(number)) return '0.00'
			
			return number.toLocaleString('zh-CN', {
				minimumFractionDigits: 2,
				maximumFractionDigits: 2
			})
		},
		
		// 格式化数字
		formatNumber(num) {
			if (num === null || num === undefined) return '0'
			
			const number = parseFloat(num)
			if (isNaN(number)) return '0'
			
			return number.toLocaleString('zh-CN')
		},
		
		// 显示错误信息
		showError(message) {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 2000
			})
		},
		
		// 导出数据
		async handleExport() {
			try {
				uni.showLoading({
					title: '导出中...'
				})
				
				const params = {
					dateType: this.dateType,
					selectedDate: this.selectedDate,
					keyword: this.searchKeyword,
					exportType: 'excel'
				}
				
				// 模拟导出过程
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '导出成功',
						icon: 'success'
					})
				}, 2000)
				
			} catch (error) {
				uni.hideLoading()
				console.error('导出失败:', error)
				this.showError('导出失败')
			}
		}
	},
	
	// 页面卸载时清除定时器
	beforeDestroy() {
		if (this.searchTimer) {
			clearTimeout(this.searchTimer)
		}
	}
}
